「 case 」表達式是 Elixir 控制流程的基石。與指令式(imperative)的 switch 語句不同, case 它是一個函數式表達式,會返回匹配分支的結果,讓開發者能立即解構如 map 與 tuple 這類複雜資料型態,同時強制執行完全匹配的邏輯。
1. 模式比對與變數繫結
「 case 表達式可讓你將一個值與一組模式進行比對。它會執行第一個匹配到的模式所對應的程式碼,並 回傳該程式碼的結果 你也可以在比對過程中繫結變數,以便於即時使用於分支邏輯中。
case dave do
%{state: some_state} = person ->
IO.puts "#{person.name} 居住在 #{some_state}"
end
%{state: some_state} = person ->
IO.puts "#{person.name} 居住在 #{some_state}"
end
2. 視覺化邏輯流程
3. 守護條件與完整性
透過使用 when 關鍵字,你可以為結構化比對加入判斷式邏輯(例如, is_number(age) and age >= 21)。Elixir 強制要求每個可能的輸入都必須有對應的匹配;若無任何模式符合,就會觸發 CaseClauseError 錯誤。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
Rewrite the FizzBuzz example using Elixir's
case expression for a number n.case {rem(n,3), rem(n,5)} do {0,0}->'FizzBuzz'; {0,_}->'Fizz'; {_,0}->'Buzz'; _->n end
case n do 15 -> 'FizzBuzz'; 3 -> 'Fizz'; 5 -> 'Buzz' end
case rem(n, 15) == 0 do true -> 'FizzBuzz' end
case n when rem(n, 15) == 0 -> 'FizzBuzz' end
✅ Correct!
Correct. By matching against a tuple of remainders, we elegantly handle all FizzBuzz conditions.❌ Incorrect
Think about creating a tuple {rem(n, 3), rem(n, 5)} and matching against {0, 0}, {0, _}, etc.QUESTION 2
What is the purpose of the
mix.exs file in the Elixir project ecosystem?To store only the source code of the application.
To define project metadata, versioning, and external dependencies.
To serve as the main entry point for the executable binary.
To configure the database connection strings exclusively.
✅ Correct!
Exactly. mix.exs is the central configuration file for your Mix project.❌ Incorrect
mix.exs manages project metadata and the dependency list (deps).QUESTION 3
According to project logic rules, where should you place additional source files belonging to the 'Issues' namespace in a project named 'issues'?
Directly in the project root.
Inside the test/ directory.
In the lib/issues/ subdirectory.
In a folder named src/.
✅ Correct!
Correct. The convention is lib/[project_name]/ for namespaced modules.❌ Incorrect
Elixir convention dictates using lib/ followed by a subdirectory named after the project.QUESTION 4
Which command allows you to see all available tasks managed by the Mix utility?
mix help
mix list
elixir --tasks
mix show
✅ Correct!
mix help provides a comprehensive list of all built-in and project-specific tasks.❌ Incorrect
Try mix help at your terminal to see the task registry.QUESTION 5
What happens if a
case expression receives a value that matches none of its patterns and there is no _ catch-all?It returns nil.
It returns false.
It raises a CaseClauseError.
The program enters an infinite loop.
✅ Correct!
Elixir enforces exhaustiveness. If no match is found, the runtime crashes to prevent invalid states.❌ Incorrect
Functional logic requires a defined outcome. Without a match, Elixir raises an error.Case Study: Managing Project Initialization
Professional Tooling and Structure
You are initializing a new project called 'issues' to track GitHub repository data. You need to structure the project using Mix, handle file operations for configuration, and compare different branching strategies.
Q
1. Provide the command to create the project skeleton and describe the command to enter the environment with project modules loaded.
Solution:
Run
Run
mix new issues to create the directory structure. To load the project into a REPL, navigate to the directory and run iex -S mix.Q
2. Compare using 'case' vs 'cond' for handling FizzBuzz. Which is easier to maintain if we add more divisors?
Solution:
While
While
cond evaluates Boolean expressions, case is often cleaner for pattern matching multiple variables simultaneously (like the remainder tuple). However, separate functions with guard clauses are the most maintainable as they isolate logic for each specific 'hit'.Q
3. In a project named 'issues', where should a module named 'Issues.Cli' be saved following standard conventions?
Solution:
It should be saved in
It should be saved in
lib/issues/cli.ex to match the namespace hierarchy.